package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.entity.Doctor;
import com.etoak.exception.CustomException;
import com.etoak.mapper.DoctorMapper;
import com.etoak.service.DoctorService;
import com.etoak.vo.PageVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DoctoerServiceImpl extends ServiceImpl<DoctorMapper, Doctor> implements DoctorService {
    @Override
    public Doctor getByName(String name) {
        return lambdaQuery().eq(Doctor::getName, name).one();
    }

    @Override
    public void add(Doctor doctor) {
        if (ObjectUtils.isNotEmpty(getByName(doctor.getName()))) {
            throw new CustomException("该医生已存在！");
        }

        this.save(doctor);
    }


    @Override
    public PageVO<Doctor> list(int pageNum, int pageSize, Doctor doctor) {
        PageHelper.startPage(pageNum, pageSize);
        List<Doctor> dishesVOList = baseMapper.getList(doctor);
        PageInfo<Doctor> pageInfo = new PageInfo<>(dishesVOList);
        return new PageVO<>(pageInfo.getTotal(), dishesVOList);
    }

    /**
     * 更新医生信息
     * @param id 医生id
     * dishes 医生参数
     * @param doctor
     */
    @Override
    public void update(int id, Doctor doctor) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("医生不存在！");
        }
        String doctorName = doctor.getName();
        if (StringUtils.isNotBlank(doctorName)) {
            Doctor saveDoctor = getByName(doctorName);
            if (ObjectUtils.isNotEmpty(saveDoctor) && !saveDoctor.getId().equals(id)) {
                throw new CustomException("医生名称重复！");
            }
        }
        doctor.setId(id);

        this.updateById(doctor);
    }

    @Override
    public void delete(int id) {
        if (ObjectUtils.isEmpty(getById(id))) {
            throw new CustomException("医生不存在！");
        }
        this.removeById(id);
    }
}
